package com.example.bookstore.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JdbcUtils {
    private static DataSource ds;

    static {
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream("F:\\JavaFiles\\bookstore\\src\\main\\resources\\druid.properties"));
            ds = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
    //获取连接
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }

    public static void close(Connection connection) throws SQLException {
        if(connection != null){
            connection.close();
        }
    }

    public static void close(ResultSet resultSet, Statement statement, Connection connection) throws SQLException {
        if(resultSet != null){
            resultSet.close();
        }
        if(statement != null){
            statement.close();
        }
        if(connection != null){
            connection.close();
        }
    }
}
